# -*- coding:utf-8 -*-
import Pluto,struct,codecs,os,fnmatch

fl=Pluto.walk('script\\field')
for fn in fl:
        if not fnmatch.fnmatch(fn,'*.bin'):
                continue
        print fn
        fp=open(fn,'rb')
        head=fp.read(4)
        if head!='DNGC':
                fp.close()
                os.remove(fn)
                continue
        fp.seek(4)
        num=struct.unpack('i',fp.read(4))[0]
        tar=codecs.open(fn+'.txt','wb','utf16')
        for i in xrange(num):
                fp.seek(8+i*4)
                offset=struct.unpack('i',fp.read(4))[0]
                nextoffset=struct.unpack('i',fp.read(4))[0]
                if i==num-1:
                        nextoffset=Pluto.size(fn)
                fp.seek(offset)
                string=[]
                #string.append('{%04x}'%(struct.unpack('H',fp.read(2))))
                fp.read(2)
                while True:
                        newoffset=fp.tell()
                        #print '%08x'%newoffset
                        if newoffset>=nextoffset-2:
                                break
                        byte=fp.read(1)
                        if ord(byte)<0x80 and ord(byte)>=0x20:
                                string.append(byte)
                        elif byte=='\x00':
                                if fp.read(1)=='\x00':
                                        string.append('\r\n')
                                        #string.append('{%04x}'%(struct.unpack('h',fp.read(2))))
                                        fp.read(2)
                                else:
                                        fp.seek(newoffset+1)
                                        string.append('\r\n')
                                        #string.append('{%04x}'%(struct.unpack('h',fp.read(2))))
                                        fp.read(2)
                        else:
                                fp.seek(newoffset)
                                char=fp.read(2)
                                string.append(char.decode('sjis'))
                #print ''.join(string)
                tar.write('No.%d'%i+'\r\n'+u'－'*18+'\r\n'+''.join(string)+'\r\n'+u'－'*18+'\r\n'*2)
        
        fp.close()
        tar.close()